package com.danke.banner.demo.banner;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.danke.banner.demo.entity.RecyclerBannerBean;
import com.danke.lib.banner.widget.banner.BaseIndicatorBanner;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2020/3/26 10:42
 */
public class RecyclerItemBanner extends BaseIndicatorBanner<String, RecyclerItemBanner> {

    private RecyclerBannerBean mData;

    public RecyclerItemBanner(Context context) {
        super(context);
        init();
    }

    public RecyclerItemBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RecyclerItemBanner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOnStateChangedListener(new OnStateChangedListener() {
            @Override
            public void onDetachedFromWindow(int currentPosition) {
                if (mData != null) {
                    mData.selectedPosition = currentPosition;
                }
            }
        });
    }

    @Override
    public View onCreateItemView(int position) {
        ImageView ivBanner = new ImageView(getContext());
        ivBanner.setScaleType(ImageView.ScaleType.FIT_XY);
        try {
            // banner宽高撑满父布局，父布局需要设置好宽高比例
            ivBanner.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        } catch (Exception e) {
        }

        final String img = getData().get(position);

        Glide.with(mContext)
                .load(img)
                .placeholder(new ColorDrawable(Color.parseColor("#555555")))
                .into(ivBanner);

        return ivBanner;
    }

    public void setData(RecyclerBannerBean data) {
        if (data == null || data.imgs == null || data.imgs.isEmpty()) {
            return;
        }
        mData = data;
        setSource(data.imgs).startScroll(data.selectedPosition);
    }
}
